<template>
  <div class="list-container">
    <!-- 头部搜索和操作栏 -->
    <div class="list-header">
      <div class="search-form">
        <div class="search-form-item">
          <label>订单ID</label>
          <el-input v-model="searchForm.orderId" placeholder="请输入订单ID" clearable @keyup.enter="handleSearch" />
        </div>
        <div class="search-form-item">
          <label>支付方式</label>
          <el-select v-model="searchForm.paymentMethod" placeholder="请选择支付方式" clearable @change="handleSearch">
            <el-option label="支付宝" value="支付宝" />
            <el-option label="微信" value="微信" />
            <el-option label="货到付款" value="货到付款" />
          </el-select>
        </div>
        <div class="search-form-item">
          <label>订单状态</label>
          <el-select v-model="searchForm.orderStatus" placeholder="请选择订单状态" clearable @change="handleSearch">
            <el-option label="待付款" value="待付款" />
            <el-option label="待发货" value="待发货" />
            <el-option label="配送中" value="配送中" />
            <el-option label="已完成" value="已完成" />
            <el-option label="已取消" value="已取消" />
          </el-select>
        </div>
        <div class="search-actions">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleAdd">新增订单</el-button>
          <el-button type="danger" @click="handleBatchDelete" :disabled="multipleSelection.length === 0">批量删除</el-button>
        </div>
      </div>
    </div>

    <!-- 表格内容区域 -->
    <div class="list-content">
      <div class="list-table">
        <div class="table-scroll-wrapper" ref="scrollWrapper">
          <el-table
            ref="multipleTableRef"
            :data="tableData"
            style="width: 100%"
            border
            v-loading="loading"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column prop="orderId" label="订单ID" min-width="100" align="center" />
            <el-table-column prop="goodId" label="商品ID" min-width="100" align="center" />
            <el-table-column prop="amount" label="数量" min-width="80" align="center" />
            <el-table-column prop="totalPrice" label="总价" min-width="100" align="center">
              <template #default="scope">
                ¥{{ scope.row.totalPrice?.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="paymentMethod" label="支付方式" min-width="100" align="center">
              <template #default="scope">
                <el-tag :type="getPaymentMethodTag(scope.row.paymentMethod)">
                  {{ scope.row.paymentMethod || '未知' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="orderStatus" label="订单状态" min-width="100" align="center">
              <template #default="scope">
                <el-tag :type="getOrderStatusTag(scope.row.orderStatus)">
                  {{ scope.row.orderStatus }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="orderTime" label="下单时间" min-width="180" align="center">
              <template #default="scope">
                {{ formatDateTime(scope.row.orderTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="200" fixed="right" align="center">
              <template #default="scope">
                <div class="action-buttons">
                  <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
                  <el-button 
                    size="small" 
                    type="danger" 
                    @click="handleDelete(scope.row)"
                  >删除</el-button>
                  <el-dropdown trigger="click" @command="(cmd) => handleStatusChange(scope.row, cmd)">
                    <el-button size="small" type="warning">
                      状态 <el-icon class="el-icon--right"><arrow-down /></el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item command="待付款" :disabled="scope.row.orderStatus === '待付款'">待付款</el-dropdown-item>
                        <el-dropdown-item command="待发货" :disabled="scope.row.orderStatus === '待发货'">待发货</el-dropdown-item>
                        <el-dropdown-item command="配送中" :disabled="scope.row.orderStatus === '配送中'">配送中</el-dropdown-item>
                        <el-dropdown-item command="已完成" :disabled="scope.row.orderStatus === '已完成'">已完成</el-dropdown-item>
                        <el-dropdown-item command="已取消" :disabled="scope.row.orderStatus === '已取消'">已取消</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <input 
            type="range" 
            class="horizontal-scroll" 
            min="0" 
            max="100" 
            value="0"
            @input="handleScroll"
            v-if="showScrollbar"
        />
      </div>
      
      <!-- 分页 -->
      <div class="list-footer">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 弹窗组件 -->
    <OrderDialog
      v-model:visible="dialogVisible"
      :is-edit="isEdit"
      :order-data="currentOrder"
      :loading="dialogLoading"
      @success="handleDialogSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import { getOrderList, addOrder, updateOrder, deleteOrder, batchDeleteOrders, updateOrderStatus } from '@/api/order'
import OrderDialog from '@/components/dialogs/OrderDialog.vue'
import '@/assets/css/table-list.css'

// 表格相关
const multipleTableRef = ref(null)
const tableData = ref([])
const loading = ref(false)
const multipleSelection = ref([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  orderId: '',
  paymentMethod: '',
  orderStatus: ''
})

// 弹窗相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentOrder = ref(null)
const dialogLoading = ref(false)

// 滚动条相关
const scrollWrapper = ref(null)
const showScrollbar = ref(false)

// 生命周期
onMounted(() => {
  fetchList()
  window.addEventListener('resize', checkScrollbar)
})

onUnmounted(() => {
  window.removeEventListener('resize', checkScrollbar)
})

// 获取列表数据
const fetchList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      orderId: searchForm.orderId || undefined,
      paymentMethod: searchForm.paymentMethod || undefined,
      orderStatus: searchForm.orderStatus || undefined
    }
    
    const res = await getOrderList(params)
    if (res.success) {
      tableData.value = res.data.data
      total.value = res.data.total
      
      nextTick(() => {
        checkScrollbar()
      })
    } else {
      ElMessage.error(res.msg || '获取订单列表失败')
    }
  } catch (error) {
    console.error('Fetch error:', error)
    ElMessage.error('获取数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 搜索和重置
const handleSearch = () => {
  currentPage.value = 1
  fetchList()
}

const handleReset = () => {
  searchForm.orderId = ''
  searchForm.paymentMethod = ''
  searchForm.orderStatus = ''
  handleSearch()
}

// 增删改查操作
const handleAdd = () => {
  isEdit.value = false
  currentOrder.value = null
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEdit.value = true
  currentOrder.value = { ...row }
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除订单 ${row.orderId} 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const res = await deleteOrder(row.orderId)
      if (res.success) {
        ElMessage.success('删除成功')
        fetchList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      ElMessage.error('操作失败')
    }
  })
}

const handleBatchDelete = () => {
  if (multipleSelection.value.length === 0) return
  
  ElMessageBox.confirm(
    `确定要批量删除选中的 ${multipleSelection.value.length} 个订单吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const ids = multipleSelection.value.map(item => item.orderId)
      const res = await batchDeleteOrders(ids)
      if (res.success) {
        ElMessage.success('批量删除成功')
        fetchList()
      } else {
        ElMessage.error(res.msg || '批量删除失败')
      }
    } catch (error) {
      ElMessage.error('操作失败')
    }
  })
}

const handleStatusChange = async (row, status) => {
  try {
    const res = await updateOrderStatus(row.orderId, status)
    if (res.success) {
      ElMessage.success('状态更新成功')
      fetchList()
    } else {
      ElMessage.error(res.msg || '状态更新失败')
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 弹窗回调
const handleDialogSuccess = async (formData) => {
  dialogLoading.value = true
  try {
    let res
    if (isEdit.value) {
      res = await updateOrder(formData.orderId, formData)
    } else {
      res = await addOrder(formData)
    }
    
    if (res.success) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      dialogVisible.value = false
      fetchList()
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    dialogLoading.value = false
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchList()
}

// 表格选择
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 格式化工具
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  // 兼容处理后端可能返回的 T 格式
  return dateTime.replace('T', ' ').substring(0, 19)
}

const getPaymentMethodTag = (method) => {
  const map = {
    '支付宝': 'primary',
    '微信': 'success',
    '货到付款': 'warning'
  }
  return map[method] || 'info'
}

const getOrderStatusTag = (status) => {
  const map = {
    '待付款': 'danger',
    '待发货': 'warning',
    '配送中': 'primary',
    '已完成': 'success',
    '已取消': 'info'
  }
  return map[status] || ''
}

// 滚动条逻辑
const checkScrollbar = () => {
  if (scrollWrapper.value) {
    const element = scrollWrapper.value.querySelector('.el-table__body-wrapper') || scrollWrapper.value
    showScrollbar.value = element.scrollWidth > element.clientWidth
  }
}

const handleScroll = (e) => {
  if (scrollWrapper.value) {
    const wrapper = scrollWrapper.value.querySelector('.el-table__body-wrapper')
    if (wrapper) {
      const maxScroll = wrapper.scrollWidth - wrapper.clientWidth
      wrapper.scrollLeft = (e.target.value / 100) * maxScroll
    }
  }
}
</script>
